package com.bigfreakindeals.Activities;

import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Util;

import com.bigfreakindeals.Activities.FaceBookShareActivity;
import com.bigfreakindeals.Activities.FaceBookShareActivity.myDialogListener;
import com.bigfreakindeals.Activities.SessionEvents.AuthListener;
import com.bigfreakindeals.Activities.SessionEvents.LogoutListener;
import com.bigfreakindeals.Application.ApplicationEx;
import com.bigfreakindeals.Common.Constant;
import com.bigfreakindeals.Common.Tools;
import com.bigfreakindeals.Controller.TwitterHelper;
import com.bigfreakindeals.Models.Company;
import com.bigfreakindeals.Protocols.SoapHandlers.FAQHandler;

import com.bigfreakindeals.R;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources.Theme;
import android.graphics.Bitmap;
import android.media.FaceDetector.Face;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

/**
 * @author abhinava_srivastava
 */

public class FaceBookShareActivity extends Activity implements OnClickListener, DialogListener {

	String APP_API_ID = "134938833247844";
	Facebook facebook = new Facebook("134938833247844"); // Application ID of your app at facebook
	AsyncFacebookRunner asyncRunner = new AsyncFacebookRunner(facebook);
	String dealtitle;
	String dealcompanyname;
	String facebookurl;
	String thumbnailurl;
	boolean isLoggedIn = false;
    boolean isPostDone = false;

    
    /** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.facebookpage);
		updateUniversityTheme();
		isPostDone = false;
		authenticate();
	
		
	}
	
	public void updateUniversityTheme() {
		if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getSchoolTitle() != null) {
			TextView headerTitle = (TextView) findViewById(R.id.header_title);
			headerTitle.setText(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getSchoolName());
			headerTitle.setTextColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().color_school_font+ (-16777216));
			
		}

		LinearLayout headertopBG = (LinearLayout) findViewById(R.id.headerbg_top);
		LinearLayout headerbottomBG = (LinearLayout) findViewById(R.id.headerbg_bottom);
		
		if (ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getColor_titleBarBottomColor() > -1
				&& ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getColor_titleBarTopColor() > -1) {
			if (headerbottomBG != null)
				headerbottomBG.setBackgroundColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getColor_titleBarBottomColor()
						+ (-16777216));

			if (headertopBG != null)
				headertopBG
						.setBackgroundColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().getColor_titleBarTopColor() + (-16777216));
		}
		
		((LinearLayout)findViewById(R.id.container)).setBackgroundDrawable(Tools.getDrawableButtonGeneric(new int[]{0xffffffff, 0xffd0d0d0}, 10));
		((RelativeLayout)findViewById(R.id.main)).setBackgroundColor(ApplicationEx.getInstance().myProfile.getlastSelectedSchool().color_school_bg + (-16777216));
		
		
	}
    private void authenticate(){
		dealtitle = getIntent().getStringExtra(Constant.TAG_COMPANY_DEALTITLE);
		dealcompanyname = getIntent().getStringExtra(Constant.TAG_COMPANY_NAME);
		facebookurl = getIntent().getStringExtra(Constant.TAG_FACEBOOK_URL);
		thumbnailurl = getIntent().getStringExtra(Constant.TAG_DEAL_THUMBNAIL);
		
		facebook = new Facebook(APP_API_ID);
		
		try{
		//	facebook.logout(getParent());
		}catch (Exception e) {
			// TODO: handle exception
		}
		
		facebook.authorize(getParent(),new String[] {"publish_stream", "read_stream", "offline_access"}, new DialogListener(){
		
			@Override
			public void onComplete(Bundle values) {
				Log.d("AUTHORIZATION COMPLETE","FB ERROR. MSG: ");
				postOnWall(values.getString(Facebook.TOKEN));
			}
	
			@Override
			public void onFacebookError(FacebookError e) {
				Log.d("FACEBOOK ERROR","FB ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
				((TextView)findViewById(R.id.text)).setText("You have cancelled Facebook post to wall.");
				((Button)findViewById(R.id.button_ok)).setVisibility(View.VISIBLE);
			}
	
			@Override
			public void onError(DialogError e) {
				Log.e("ERROR","AUTH ERROR. MSG: "+e.getMessage()+", CAUSE: "+e.getCause());
				((TextView)findViewById(R.id.text)).setText("You have cancelled Facebook post to wall.");
				((Button)findViewById(R.id.button_ok)).setVisibility(View.VISIBLE);
			}
	
			@Override
			public void onCancel() {
				Log.d("CANCELLED","AUTH CANCELLED");
				((TextView)findViewById(R.id.text)).setText("You have cancelled Facebook post to wall.");
				((Button)findViewById(R.id.button_ok)).setVisibility(View.VISIBLE);
			}
		});
		((Button)findViewById(R.id.button_ok)).setOnClickListener(this);
		
	}
	
	
	//ACG
	public void postOnWall(String msg) {
         try {
        	 
        	 Bundle parameters = new Bundle();
         	
        	 JSONObject attachment = new JSONObject();
             attachment.put("name", "BigFreakinDeals");
             attachment.put("href", facebookurl);
             attachment.put("caption", dealtitle);
             attachment.put("description", dealcompanyname);

             JSONObject media = new JSONObject();
             media.put("type", "image");
             media.put("src", thumbnailurl);
             media.put("href",facebookurl);
             attachment.put("media", new JSONArray().put(media));

             
             Log.d("FACEBOOK", attachment.toString());

        	
        	 String message = "Check out this deal"+"\n"+dealcompanyname +"\n\n "+dealtitle;

        	 parameters.putString("attachment", attachment.toString());
        	 parameters.putString("message", message);

        	 facebook.dialog(FaceBookShareActivity.this.getParent(), "stream.publish", parameters, this);
        	 isPostDone = true; 
        	 ((TextView)findViewById(R.id.text)).setText("You have successfully posted on your Facebook wall.");
        	 ((Button)findViewById(R.id.button_ok)).setVisibility(View.VISIBLE);
        	 ((Button)findViewById(R.id.button_ok)).setOnClickListener(this);
        	 
				
        	 
         } catch(Exception e) {
        	 ((TextView)findViewById(R.id.text)).setText("There is an error posting"+e.getMessage());
        	 ((Button)findViewById(R.id.button_ok)).setVisibility(View.VISIBLE);
        	 ((Button)findViewById(R.id.button_ok)).setOnClickListener(this);
         }
    }

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.d("onActivityResult","onActivityResult"+requestCode+" "+resultCode);
    facebook.authorizeCallback(requestCode, resultCode, data);
}

	
	
	@Override
	public void onResume() {
		super.onResume();
		System.out.println("ONRESUME...@facebookshare");
	
		
	}

	
	@Override
	public void onDestroy() {
		super.onDestroy();

		System.out.println("ONRESUME...@destroy");
	}

	
	@Override
	public void onClick(View v) {
		
		if(v.getId() == R.id.button_ok){
			
			this.getParent().onBackPressed();	
			finish();
		}
	}
	
	


    public class myAuthListener implements AuthListener {

        public void onAuthSucceed() {
           
        }

        public void onAuthFail(String error) {
         
        }
    }

    public class myLogoutListener implements LogoutListener {
        public void onLogoutBegin() {
           Log.i("onLogoutBegin", "Logging out...");
        }

        public void onLogoutFinish() {
            Log.i("onLogoutFinish", "You have logged out! ");
        }
    }
    
    
    public class WallPostRequestListener extends BaseRequestListener {

        public void onComplete(final String response, final Object state) {
            Log.d("Facebook-Example", "Got response: " + response);
            String message = "";
            try {
                JSONObject json = Util.parseJson(response);
                message = json.getString("message");
            } catch (JSONException e) {
                Log.w("Facebook-Example", "JSON Error in response" + e.getMessage());
            } catch (FacebookError e) {
                Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
            }
            final String text = "Your Wall Post: " + message;
            FaceBookShareActivity.this.runOnUiThread(new Runnable() {
                public void run() {
                    Log.i("wall post complete: ", text);
                }
            });
        }
            
        
    }
  
    @Override  
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	System.out.println("ONKEYE");
    		if ((keyCode == KeyEvent.KEYCODE_BACK)) {
    			if(!isPostDone) {  
    				 ((TextView)findViewById(R.id.text)).setText("You have cancelled posting on your Facebook wall.");
    				 facebook.getAccessExpires();
    				 facebook.dismisDialog();
    				 return false;
    			}
   
    		}
    		return false;
    }
    public class myDialogListener extends BaseDialogListener {

        public void onComplete(Bundle values) {            
                Log.d("attachment", values.toString());

        	final String postId = values.getString("post_id");
            if (postId != null) {
                Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
                asyncRunner.request(postId, values, new WallPostRequestListener());
            
            } else {
            	((TextView)findViewById(R.id.text)).setText("No wall post made. You have cancelled Facebook post to wall.");
        		
            }
        	////
        }
    }
    /******************End*********************************************/
	@Override
	public void onComplete(Bundle values) {
		// TODO Auto-generated method stub
		
		System.out.println("wall posting is complete");
		
	}
	@Override
	public void onFacebookError(FacebookError e) {
		// TODO Auto-generated method stub
		System.out.println("wall posting is error"+e.getErrorCode()+" "+e.getMessage());
		
		
	}
	@Override
	public void onError(DialogError e) {
		// TODO Auto-generated method stub
		System.out.println("wall posting is Dialog error "+" "+e.getMessage());
		
		
	}
	@Override
	public void onCancel() {
		// TODO Auto-generated method stub
		System.out.println("wall posting is cancel");
		
		
	}
}
